<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="学生姓名：" prop="partnerId">
        <el-select v-model="dataForm.partnerId" placeholder="请选择">
          <el-option
            v-for="item in students"
            :key="item.partnerId"
            :label="item.name"
            :value="item.partnerId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="心愿名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="心愿名称"></el-input>
      </el-form-item>
      <el-form-item label="心愿类型" prop="wishType">
        <el-radio v-model="dataForm.wishType" :label="1" >个人心愿</el-radio>
        <el-radio v-model="dataForm.wishType" :label="2" >团队心愿</el-radio>
      </el-form-item>
      <el-form-item label="心愿缩略图" prop="wishInfo">
        <el-upload
          class="upload-demo"
          :file-list="fileList"
          :action="url"
          :show-file-list="true"
          :before-upload="beforeAvatarUpload"
          :on-success="wishSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">大小不超过250KB且必须是240*240</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="心愿状态" prop="wishStatus" v-if="!dataForm.id">
        <el-radio-group v-model="dataForm.wishStatus" :disabled="true">
          <el-radio :label="1">进行中</el-radio>
          <el-radio :label="2">助力完成</el-radio>
          <el-radio :label="3">寄送中</el-radio>
          <el-radio :label="5">已送达</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="心愿状态" prop="wishStatus" v-if="dataForm.id">
        <el-radio-group v-model="dataForm.wishStatus" @change="isSendInfo">
          <el-radio :label="1">进行中</el-radio>
          <el-radio :label="2">助力完成</el-radio>
          <el-radio :label="3">寄送中</el-radio>
          <el-radio :label="5">已送达</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所需学分" prop="targetCredit">
        <el-input :disabled="dataForm.wishStatus!=1" v-model.number="dataForm.targetCredit" placeholder="所需学分" @change="changeTarget"></el-input>
      </el-form-item>
      <el-form-item label="已捐学分" prop="donateCredit" v-if="dataForm.id">
        <el-input v-model="dataForm.donateCredit"   placeholder="已捐学分" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="申请理由" prop="whyUrl">
        <el-upload
          class="upload-demo"
          :file-list="fileList1"
          :action="url"
          :show-file-list="true"
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">大小不超过250KB且宽度必须是1029</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="文字版申请理由 " prop="whyText">
        <el-input v-model="dataForm.whyText" placeholder="请输入申请理由图片的文字内容 "></el-input>
      </el-form-item>
      <el-form-item label="支教老师" prop="teacherId">
        <el-select  v-model="dataForm.teacherId" placeholder="请选择" >
          <el-option
            v-for="item in projectList"
            :key="item.teacherId"
            :label="item.name"
            :value="item.teacherId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐理由 " prop="teacherWhy">
        <el-input v-model="dataForm.teacherWhy" placeholder="推荐理由 "></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        fileList: [],
        fileList1: [],
        students: [],
        // 避免重复提交
        formLock: true,
        visible: false,
        dataForm: {
          id: '',
          wishType: '',
          partnerId: "",
          partnerName:'',
          teacherId: "",
          teacherWhy: "",
          title: "",
          whyUrl: "",
          targetCredit: "",
          wishStatus: 1,
          wishFinInfo: "",
          gmtCreated: "",
          gmtUpdate: "",
          isAlive: "1",
          wishInfo:'',
          donateCredit:'',
        },
        dataRule: {
          // partnerName:[
          //      { required: true, message: "姓名不能为空", trigger: "blur" }
          // ],
          partnerId: [
            { required: true, message: "学生姓名不能为空", trigger: "blur" },

          ],
          wishType: [
            { required: true, message: "心愿类型不能为空", trigger: "blur" },

          ],
          whyText: [
            { required: true, message: "文字版申请理由不能为空", trigger: "blur" },

          ],
          teacherId: [
            { required: true, message: "推荐老师不能为空", trigger: "blur" },

          ],
          teacherWhy: [
            { required: true, message: "推荐理由 不能为空", trigger: "blur" },
          ],
          title: [
            { required: true, message: "心愿标题不能为空", trigger: "blur" },
          ],
          targetCredit: [
            { required: true, message: "积分不能为空", trigger: "blur" }
          ]
        },
        url: "",
        projectList:[],
      };
    },
    mounted() {
      this.initList()
      this.url = this.$http.adornUrl(
        `/partner/partnerwish/upload?token=${this.$cookie.get("token")}`
      );
    },
    methods: {
      initList() {
        // 学生列表
        this.$http({
          url: this.$http.adornUrl(
            `/partner/partnertargetinfo/search`
          ),
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.students = data.list
          }
        })
        // 老师列表
        this.$http({
          url: this.$http.adornUrl(`/partner/teacherinfo/search`),
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          // console.log(data)
          if (data && data.code === 0) {
            this.projectList = data.list;
          }
        });
      },
      changeTarget() {
        if(this.dataForm.donateCredit && this.dataForm.targetCredit==this.dataForm.donateCredit){
          this.dataForm.wishStatus = 2
        }
      },
      init(data) {
        this.dataForm = JSON.parse(JSON.stringify(data)) || { wishStatus: 1 }
        // 初始化2个图片
        if(this.dataForm.wishInfo) {
          this.fileList = [
            {
              name: this.dataForm.wishInfo,
              url: this.dataForm.wishInfo
            }
          ]
        } else {
          this.fileList = []
        }
        if(this.dataForm.whyUrl) {
          this.fileList1 = [
            {
              name: this.dataForm.whyUrl,
              url: this.dataForm.whyUrl
            }
          ]
        } else {
          this.fileList1 = []
        }
        this.visible = true
      },
      isSendInfo(wishStatus) {
        if( wishStatus === 5 ) {
          // 判断有没有寄送信息
        }
      },
      handleAvatarSuccess(response, file, fileList) {
        this.fileList1 = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.whyUrl = response.url;
        } else {
          this.$message.error(response.msg);
        }
      },
      wishSuccess(response, file, fileList) {
        this.fileList = [fileList[fileList.length-1]];
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.wishInfo = response.url;
        } else {
          this.$message.error(response.msg);
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error("请上传图片!");
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 240;
          let height = 240;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的心愿缩略图必须是240*240!");
            return Promise.reject();
          }
        );
        return isJPG  && isSize;
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error("请上传图片！");
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 1029;
          // let height = 160;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width ;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的心愿缩略图的宽度必须是1029!");
            return Promise.reject();
          }
        );
        return isJPG  && isSize;
      },
      // 表单提交
      dataFormSubmit() {
        if(this.dataForm.donateCredit && this.dataForm.targetCredit<this.dataForm.donateCredit){
          this.$message.error('所需学分要大于已捐学分');
          return false
        }
        if(!this.dataForm.wishInfo){
          this.$message.error('请上传心愿缩略图');
          return false
        }
        if(!this.dataForm.whyUrl){
          this.$message.error('请上传心申请理由');
          return false
        }
        if(this.formLock) {
          this.$refs["dataForm"].validate(valid => {
            if (valid) {
              this.formLock = false
              this.$http({
                url: this.$http.adornUrl(
                  `/partner/partnerwish/${!this.dataForm.id ? "save" : "update"}`
                ),
                method: "post",
                data: this.$http.adornData(this.dataForm)
              }).then(({ data }) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit("refreshDataList",this.dataForm.partnerId);
                      setTimeout(()=>{
                        this.formLock = true
                      }, 500)
                    }
                  });
                } else {
                  this.formLock = true
                  this.$message.error(data.msg);
                }
              });
            }
          });
        }
      }
    }
  };
</script>
